package mapred.example.model;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Link {

    private int metaType = 0;

    private String url = "";

    private int anchorType = 0;

    private List<String> text = new ArrayList<String>();

    private Link(int metaType, String url, int anchorType, String... text) {
        this.metaType = metaType;
        this.url = url;
        this.anchorType = anchorType;
        this.text = Arrays.asList(text);
    }

    public static Link newInstanceFromParser(String link) {
        try {
            int pos = link.indexOf("\t");
            String k = link.substring(0, pos);
            String v = link.substring(pos + 1);
            
            pos = k.indexOf('\1');
            int metaType = Integer.parseInt(k.substring(0, pos));
            String url = k.substring(pos + 1);
    
            if (isValidUrl(url)) {
                pos = v.indexOf('\t');
                int anchorType = Integer.parseInt(v.substring(0, pos));
    
                pos = v.indexOf('\1');
                String[] text = v.substring(pos + 1).split("\t");
    
                return new Link(metaType, url, anchorType, text);
            } else {
                return null;
            }
        } catch (RuntimeException e) {
            throw new RuntimeException(link, e);
        }
    }

    public int getMetaType() {
        return metaType;
    }

    public String getUrl() {
        return url;
    }

    public int getAnchorType() {
        return anchorType;
    }

    public List<String> getText() {
        return text;
    }

    private static boolean isValidUrl(String url) {
        return (url.startsWith("http://") || url.startsWith("https://"));
    }

}
